Ruby ハッシュ
#Ruby
code:rb
fruits = { apple: 100, banana: 200, cherry: 300 }
fruits:orange #=> nil # 存在しないキーを指定するとnilが返る
fruits:apple #=> 100
fruits.keys #=> :apple, :banana, :cherry
fruits.values #=> 100, 200, 300
fruits.has_key?(:cherry) #=> true
# 要素追加・上書き
fruits:grape = 400
fruits #=> {:apple=>100, :banana=>200, :cherry=>300, :grape=>400}
# []=のエイリアス、store
fruits.store(:grape, 400)
#要素削除
fruits.delete(:apple)
fruits #=> {:banana=>200, :cherry=>300}
# ハッシュの展開
{ orange: 50, fruits } #=> SyntaxError
{ orange: 50, **fruits } #=> {:orange=>50, :apple=>100, :banana=>200, :cherry=>300}
# ハッシュの結合
hash = { orange: 50 }
hash.merge(fruits) #=> {:orange=>50, :apple=>100, :banana=>200, :cherry=>300}
# 配列に変換
ary = fruits.to_a #=> :apple, 100], :banana, 200, [:cherry, 300
ハッシュの繰り返し処理
code:rb
fruits = { apple: 100, banana: 200, cherry: 300 }
fruits.each { |key, value| puts "#{key}は#{value}円です。" }
fruits.each_key { |key| puts key }
fruits.each_value { |value| puts value }
# mapで返ってくるのは「配列」
fruits.map { |key, value| v * 2 } #=> 200, 400, 600
fruits.map { |k, v| k, v * 2 } #=> :apple, 200], :banana, 400, [:cherry, 600
# to_hでハッシュに変換
fruits.map { |k, v| k, v * 2 }.to_h #=> {:apple=>200, :banana=>400, :cherry=>600}